package com.zch.starter.opentelemetry.agent.mode.springboot.starter.interceptor;

import com.zch.starter.opentelemetry.agent.mode.springboot.starter.utils.TraceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TraceIdInterceptor implements HandlerInterceptor {
    public static final String TRACE_ID_KEY = "X-ZCH-Access-Trace-Id";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.addHeader(TRACE_ID_KEY, TraceUtils.getTraceId());
        //设置请求头
        String headTraceId = request.getHeader(TRACE_ID_KEY);
        if(StringUtils.isBlank(headTraceId)||!TraceUtils.isValidTraceId(headTraceId)){
            //向请求的attribute 设置值
            request.setAttribute(TRACE_ID_KEY, TraceUtils.getTraceId());
        }
        return Boolean.TRUE;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //postHandler do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        response.setHeader(TRACE_ID_KEY, TraceUtil.getTraceId());
    }
}
